package com.jry.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jry.common.core.constant.HttpStatus;
import com.jry.common.core.constant.SecurityConstants;
import com.jry.common.core.domain.R;
import com.jry.common.core.utils.StringUtils;
import com.jry.common.core.web.domain.AjaxResult;
import com.jry.demo.domain.DemoVo;
import com.jry.demo.mapper.DemoMapper;
import com.jry.demo.service.DemoTestService;
import com.jry.system.api.RemoteUserService;
import com.jry.system.api.domain.SysUser;
import com.jry.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class DemoTestServiceImpl extends ServiceImpl<DemoMapper, DemoVo> implements DemoTestService {

    @Resource
    private RemoteUserService remoteUserService;

    @Override
    public Map<String, Object> add(DemoVo demoVo) {
        Map<String, Object> res = new HashMap<>();
        String msg = null;
        int code = 0;
        try {
            boolean flag = save(demoVo);
            code = flag ? HttpStatus.SUCCESS : HttpStatus.BAD_REQUEST;
        } catch (Exception e) {
            msg = e.getMessage();
            code = HttpStatus.ERROR;
            log.error("DemoTestServiceImpl test error: {}", e.getMessage());
        }
        res.put(AjaxResult.MSG_TAG, msg);
        res.put(AjaxResult.CODE_TAG, code);
        return res;
    }

    @Override
    public List<DemoVo> getList(DemoVo demoVo) {
        LambdaQueryWrapper<DemoVo> wrapper = makeLambdaQueryWarpper(demoVo);
        return list(wrapper);
    }

    private LambdaQueryWrapper<DemoVo> makeLambdaQueryWarpper(DemoVo demoVo) {
        LambdaQueryWrapper<DemoVo> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(demoVo.getName())) {
            wrapper.like(DemoVo::getName, demoVo.getName());
        }
        if(StringUtils.isNotEmpty(demoVo.getSex())) {
            wrapper.eq(DemoVo::getSex, demoVo.getSex());
        }
        if(StringUtils.isNotNull(demoVo.getAge()) && demoVo.getAge() != 0) {
            wrapper.eq(DemoVo::getAge, demoVo.getAge());
        }
        return wrapper;
    }

    @Override
    public LoginUser getSystemUser(String userName) {
        R<LoginUser> userInfo = remoteUserService.getUserInfo(userName, SecurityConstants.INNER);
        return userInfo.getData();
    }
}
